// Copyright (C) 2012 Volkov Zachar
// This file is part of the "zAxis Game Engine".
// For conditions of distribution and use, see copyright notice zx_Common.hpp

#include "zx_Async.hpp"
#include <Windows.h>

namespace zx {

//----------------------------------------------------------------------------//
//----------------------------------------------------------------------------//
GlobalMutex::GlobalMutex( const String& _name )
{
     char _tmp[ MAX_PATH + 1 ];
     uint _length = Min< uint >( MAX_PATH, _name.length() ); 
     strncpy( _tmp, _name.c_str(), _length );
     _length = CharLowerBuffA( _tmp, _length );
     _tmp[ _length ] = 0;

     for( uint i = 0; i < _length; ++ i )
     {
          if( _tmp[ i ] == '\\' ) { _tmp[ i ] = '/'; }
     }

     m_name = _tmp;

     m_handle = CreateMutex( 0, 0, m_name.c_str() );
}
//----------------------------------------------------------------------------//
GlobalMutex::~GlobalMutex( void )
{
     CloseHandle( m_handle );
}
//----------------------------------------------------------------------------//
bool GlobalMutex::Lock( int _time_ms )
{
     return WaitForSingleObject( m_handle, zxChoose( _time_ms < 0, INFINITE, _time_ms ) ) != WAIT_TIMEOUT; 
}
//----------------------------------------------------------------------------//
void GlobalMutex::Unlock( void )
{
     ReleaseMutex( m_handle );
}
//----------------------------------------------------------------------------//
//----------------------------------------------------------------------------//

} // namespace zx
